import "dart:convert";

import "package:ct_pa_majordomo/pages/mine/withdraw/api.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/material.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/utils/index.dart";

class WithdrawDetailListPage extends StatefulWidget {
  const WithdrawDetailListPage({super.key});

  @override
  State<WithdrawDetailListPage> createState() => _WithdrawDetailListPageState();
}

class _WithdrawDetailListPageState extends State<WithdrawDetailListPage> {
  final ScrollController _scrollController = ScrollController();
  final Map<String, dynamic> _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "apartmentId": 0,
  };
  int _apartmentId = -1;

  List _detailList = [];
  bool _isLoading = false;
  bool _hasMore = true;
  bool _disposed = false;

  @override
  void initState() {
    super.initState();
    
    String apartment = storage.getString("apartment") ?? "";
    if (apartment != "") {
      _apartmentId = jsonDecode(apartment)["apartmentId"] ?? -1;
    }
    
    if (_apartmentId > 0) {
      _filter["apartmentId"] = _apartmentId;
      _loadDetailList();
    } else {
      _hasMore = false;
    }
    
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _disposed = true;
    _scrollController.dispose();
    super.dispose();
  }

  // 加载提现详细列表
  void _loadDetailList() {
    if (_apartmentId <= 0 || _disposed) {
      setState(() {
        _isLoading = false;
        _hasMore = false;
      });
      return;
    }
    
    setState(() {
      _isLoading = true;
    });
    
    withdrawApi.withdrawDetailList(_filter).then((value) {
      if (mounted && !_disposed) {
        setState(() {
          _isLoading = false;
          List newList = value["data"]["list"] ?? [];
          
          if (_filter["pageNum"] == 1) {
            _detailList = newList;
          } else {
            _detailList.addAll(newList);
          }
          
          _hasMore = newList.length >= _filter["pageSize"];
        });
      }
    }).catchError((error) {
      if (mounted && !_disposed) {
        setState(() {
          _isLoading = false;
          if (_filter["pageNum"] > 1) {
            _filter["pageNum"] = _filter["pageNum"] - 1;
          }
        });
      }
    });
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    if (_apartmentId <= 0 || _disposed) {
      return;
    }
    
    setState(() {
      _filter["pageNum"] = 1;
      _detailList.clear();
      _hasMore = true;
    });
    await Future.delayed(const Duration(milliseconds: 500));
    _loadDetailList();
  }

  // 上拉加载更多
  void _onScroll() {
    if (!mounted || _disposed || _apartmentId <= 0) return;
    
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
      if (_hasMore && !_isLoading) {
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted && !_disposed && _hasMore && !_isLoading && _apartmentId > 0) {
            _loadMore();
          }
        });
      }
    }
  }

  void _loadMore() {
    if (!_hasMore || _isLoading || _disposed || _apartmentId <= 0) return;
    
    setState(() {
      _filter["pageNum"] = _filter["pageNum"] + 1;
    });
    
    _loadDetailList();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "提现明细",
      child: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView(
          controller: _scrollController,
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            if (_detailList.isEmpty)
              Container(
                padding: const EdgeInsets.all(40),
                child: Center(
                  child: Column(
                    children: [
                      Icon(
                        _isLoading ? Icons.hourglass_empty : Icons.receipt_long,
                        size: 48,
                        color: ThemeVars.colorTextTer,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        _apartmentId <= 0 
                          ? "无效的公寓ID"
                          : _isLoading 
                            ? "加载中..."
                            : "暂无提现明细",
                        style: const TextStyle(
                          color: ThemeVars.colorTextSec,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              ..._detailList.map((detail) => _buildDetailItem(detail)),
            
            // 加载更多指示器
            if (_isLoading)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              ),
            
            // 没有更多数据提示
            if (!_hasMore && _detailList.isNotEmpty)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: Text(
                    "没有更多数据了",
                    style: TextStyle(
                      color: ThemeVars.colorTextSec,
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  // 构建明细项
  Widget _buildDetailItem(Map<String, dynamic> detail) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: ThemeVars.colorBorder,
          width: 0.5,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                detail["title"] ?? "提现明细",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                "¥${Utils.formatCurrency(detail["amount"] ?? 0)}",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: ThemeVars.colorSuccess,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "提现单号",
                style: const TextStyle(
                  fontSize: 14,
                  color: ThemeVars.colorTextSec,
                ),
              ),
              Text(
                "#${detail["withdrawId"] ?? ""}",
                style: const TextStyle(
                  fontSize: 14,
                  color: ThemeVars.colorTextSec,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "创建时间",
                style: const TextStyle(
                  fontSize: 14,
                  color: ThemeVars.colorTextSec,
                ),
              ),
              Text(
                detail["createTime"] ?? "",
                style: const TextStyle(
                  fontSize: 14,
                  color: ThemeVars.colorTextSec,
                ),
              ),
            ],
          ),
          if (detail["remark"] != null && detail["remark"].isNotEmpty) ...[
            const SizedBox(height: 8),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: ThemeVars.colorBackground,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                "备注: ${detail["remark"]}",
                style: const TextStyle(
                  fontSize: 12,
                  color: ThemeVars.colorTextSec,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
} 